import React,{ Component } from 'react'
import {
    Button,
    Row,
    Col,
    Input,
    InputNumber,
    Collapse,
    message,
    Menu,Dropdown,
} from 'antd';
import { LegionsProForm,LegionsProModal,LegionsProTableForm } from 'legions-pro-design';
import { OpenConfirm,OpenDeleteConfirm } from 'legions-lunar/antd-toolkit';
import { bind,observer } from 'legions/store-react'
import ProjectStore from '../../stores/projectStore';
import { observable,action,computed } from 'mobx';
import { observableViewModel } from 'legions/store-utils';
import {
    PropertyKeyValueFormFields,
} from '../../models/form/propertyFormModel';
import { OperationEnum } from '../../constants/enum-data';
import FormPropertyConfig from '../../components/property.config.form/formPropertyConfig';
import { shortHash } from 'legions-lunar/object-hash';
import AddCodeExpression from './addCodeExpression';
import get from 'lodash/get';
import set from 'lodash/set';
import has from 'lodash/has';
import { HlLabeledValue } from 'legions-lunar/model';
import { fullProvider,lazyInject,inject } from 'legions-control-container';
import { InstanceProTable } from 'legions-pro-design/es/LegionsProTable/interface';
import { IProTableFormColumnConfigProps } from 'legions-pro-design/es/LegionsProTableForm/interface';
import { FormRuleProperty } from 'legions-decorator/async.validator';
import { FormCanvasDomain } from '../../services/components/formCanvasDomain';
/** 下拉选项实体 */
class SelectOptionsFields extends LegionsProForm.ProFormFields<SelectOptionsFields>{
    @FormRuleProperty({
        required: true,
        name: 'keysId',
        error: 'keysId',
        desc: '',
        type: 'string',
        regex: /^[A-Z a-z]+$/,
    })
    keysId: string = void 0


    @FormRuleProperty({
        required: true,
        name: '选项值',
        error: '选项值只能为英文,数字，或组合',
        desc: '选项值',
        type: 'string',
        /* regex: /^([A-Z a-z])|(\d)|([A-Z a-z 0-9])+$/, */
        validator: (value: string,error,calback,props) => {
            const reg = /^([A-Z a-z])|(\d)|([A-Z a-z 0-9])+$/
            if (!reg.test(value)) {
                calback(error)
            }
            calback();
        }
    })
    labelKey: string = void 0

    @FormRuleProperty({
        required: true,
        name: 'labelValue',
        error: 'labelValue',
        desc: '选项标签名',
        type: 'string',
    })
    labelValue: string = void 0;

}
interface IProps {
    store?: ProjectStore;
    /** 保存事件 */
    onOkSave?: (value?: {
        data: {
            key: string;
            label: string;
            value: string;
        }[];
        type:'remote'|'local'
    }) => void;
}
class ViewModel {
    /*  @observable tableData: { id: string,labelKey: string; labelValue: string; label?: string }[] = [] */
    @observable loading: boolean = false;
}

const tableColumns = (that: AddSelectOptions): IProTableFormColumnConfigProps<SelectOptionsFields>[] => [
    { title: '选项标签名(客户端展示)',width: 160,dataIndex: 'labelValue' },
    { title: '选项值(服务端业务逻辑使用)',width: 160,dataIndex: 'labelKey' },
    {
        title: '操作',width: 120,dataIndex: 'operation',render: (text,record) => {
            const index = record['index'];
            return <div>
                <Button type="primary" onClick={() => {
                    const addSelLocalListTableForm = that.projectCommonFormRef.addSelLocalListTableForm.form;
                    if (record['isRecordEdit']) {
                        addSelLocalListTableForm.viewModel.form.validateFields((error) => {
                            if (!error) {
                                addSelLocalListTableForm.methods.updateRecordEditData(record);
                            }
                        });
                    } else {
                        addSelLocalListTableForm.methods.updateRecordEditData(record);
                    }
                }}>
                    {record['isRecordEdit'] ? '保存' : '编辑'}
                </Button>
                <Button type="danger" style={{ marginLeft: 5 }} onClick={() => {
                     const projectCommonApp = that.props.store.context.projectCommonApp;
                     const lists= projectCommonApp.computedSelectVModel.selectValueData
                    const list = [...lists];
                    list.splice(index,1);
                    projectCommonApp.updateSelectValue('local',{
                        local:list.map((item,index) => ({ ...item,index }))
                    })
                }}>删除</Button>
            </div>
        }
    },
]
@bind({ store: ProjectStore })
@observer
export default class AddSelectOptions extends Component<IProps> {
    /** 分组信息编辑模态框实例 */
    viewModel = observableViewModel<ViewModel>(new ViewModel());
    @lazyInject(FormPropertyConfig)
    public formPropertyConfig!: FormPropertyConfig

    @lazyInject(FormCanvasDomain)
    formCanvasDomain!: FormCanvasDomain

    static SelectOptionsFields = SelectOptionsFields;
    /** 分组信息表单实例 */
    constructor(props: IProps) {
        super(props);
        this.formPropertyConfig.registerAddSelectOptionsInstance(this);
    }
    get projectCommonFormRef() {
        return this.props.store.context.projectCommonApp.projectCommonFormRef;
    }
    componentDidMount() {
        console.log('componentDidMount')
    }
    onAdd() {
        const model = new SelectOptionsFields();
        const projectCommonApp = this.props.store.context.projectCommonApp;
        const list = projectCommonApp.computedSelectVModel.selectValueData;
        model.labelKey = `${list.length}`;
        model.labelValue = `legions${list.length}`;
        const newList=[
            ...list,
            {
                ...model,
            },
        ]
        projectCommonApp.updateSelectValue('local',{local:newList
        })
        this.projectCommonFormRef.addSelLocalListTableForm.form.methods.addEditRecord(model);
    }
    onDelete() {
        const rows = this.projectCommonFormRef.addSelLocalListTableForm.table.viewModel.computedSelectedRows;
        const projectCommonApp = this.props.store.context.projectCommonApp;
        if (rows.length > 0) {
            OpenDeleteConfirm({
                onOk: () => {
                    const lists= projectCommonApp.computedSelectVModel.selectValueData
                    rows.map((item) => {
                        const index = lists.findIndex((value) => value.labelKey === item['labelKey'])
                        const list = [...lists];
                        list.splice(index,1);
                        projectCommonApp.updateSelectValue('local',{
                            local:list.map((item,index) => ({ ...item,index }))
                        })
                    })
                }
            })
        } else {
            message.warn('请先选择需要删除的数据')
        }
    }
    render() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        const projectCommonApp = this.props.store.context.projectCommonApp;
        const dataType = projectCommonApp.computedSelectVModel ? projectCommonApp.computedSelectVModel.dataType : null;
        return (
            <React.Fragment>
                <LegionsProModal
                    closable={false}
                    maskClosable={false}
                    footer={(<React.Fragment>
                        <Button onClick={() => {
                            OpenConfirm({
                                title: '关闭',
                                content: '如果不设置,将无法完整使用组件功能,您确定要取消属性设置吗？',
                                onOk: () => {
                                    projectCommonApp.formSelectValueModalRef.viewModel.visible = false;
                                }
                            })
                        }}>取消</Button>
                        <Button type="primary" onClick={() => {
                            if (dataType === 'local') {
                                this.projectCommonFormRef.addSelLocalListTableForm.form.viewModel.form.validateFields((err,value: PropertyKeyValueFormFields) => { 
                                    if (!err) {
                                        const arr = projectCommonApp.computedSelectVModel.selectValueData.map(item => { return { key: item.labelKey,label: item.labelValue,value: item.labelValue } })
                                        this.props.onOkSave && this.props.onOkSave({
                                            data: arr,
                                            type:dataType
                                        })
                                        message.success('添加成功')
                                        projectCommonApp.formSelectValueModalRef.viewModel.visible = false;
                                    }
                                })
                                
                            }
                            if (dataType==='remote') {
                                this.projectCommonFormRef.addSelAutoQueryForm.viewModel.form.validateFields((err,value: PropertyKeyValueFormFields) => { 
                                    if (!err) {
                                        this.props.onOkSave && this.props.onOkSave({
                                            data: [],
                                            type:dataType
                                        });
                                        message.success('添加成功')
                                        projectCommonApp.formSelectValueModalRef.viewModel.visible = false;
                                    }
                                })
                            }
                            
                        }}>保存</Button>
                    </React.Fragment>)}
                    onReady={(value) => {
                        const width = 750;
                        projectCommonApp.formSelectValueModalRef = value;
                        projectCommonApp.formSelectValueModalRef.viewModel.okText = '保存';
                        projectCommonApp.formSelectValueModalRef.viewModel.width = width;
                    }}>
                    <React.Fragment>
                        {dataType === 'local' && <LegionsProTableForm<SelectOptionsFields,PropertyKeyValueFormFields>
                            proFormConfig={
                                {
                                    controls: this.formPropertyConfig.createAddSelectOptionsConfig(),
                                    onReady: (_,formRef) => {
                                        formRef.viewModel.enableEnterSwitch = true;
                                        this.projectCommonFormRef.addSelLocalListTableForm.form=Object.assign(formRef,{ that: this });
                                    },
                                }
                            }
                            proTableConfig={{
                                columns: tableColumns(this),
                                //@ts-ignore
                                dataSource: projectCommonApp.computedSelectVModel.selectValueData,
                                uniqueKey: 'legionsTableFormItemKey',
                                onReady: (formRef) => {
                                    this.projectCommonFormRef.addSelLocalListTableForm.table=Object.assign(formRef,{ that: this });
                                },
                                footer: () => <React.Fragment><Button onClick={() => {
                                    this.onAdd()
                                }}>添加</Button><Button style={{ marginLeft: '5px' }} type="danger" onClick={() => {
                                    this.onDelete()
                                }}>删除</Button></React.Fragment>
                            }}
                            onChange={(dataList) => {
                                projectCommonApp.updateSelectValue('local',{
                                    local:dataList
                                })
                            }}
                        ></LegionsProTableForm>
                        }
                        {
                            dataType === 'remote' && <LegionsProForm
                            <PropertyKeyValueFormFields>
                                InputDataModel={PropertyKeyValueFormFields}
                                mapPropsToFields={(props) => {
                                    return new PropertyKeyValueFormFields(props) // 实际处理结果实体
                                }}
                                onFieldsChange={(props,formFields: PropertyKeyValueFormFields) => {
                                    this.projectCommonFormRef.addSelAutoQueryForm.store.updateFormInputData(this.projectCommonFormRef.addSelAutoQueryForm.uid,formFields)
                                }}
                                colCount={1}
                                controls={this.formPropertyConfig.createAddSelectOptionsValue()}
                                onReady={(_,formRef) => {
                                    formRef.viewModel.enableEnterSwitch = true;
                                    this.projectCommonFormRef.addSelAutoQueryForm = Object.assign(formRef,{ that: this });
                                }}
                        ></LegionsProForm>
                        }
                    </React.Fragment>
                </LegionsProModal>
                <AddCodeExpression
                    onReady={(value) => {
                        projectCommonApp.formAddKeyValueCodeExpressionModalRef = value;
                    }}
                    onCancel={() => {
                        projectCommonApp.formSelectValueModalRef.viewModel.visible = true;
                    }}
                    onOk={() => {
                        /**  */
                        const mapjson = { transform: 'transform',params: 'params',token: 'token',mappingEntity:'mappingEntity' }
                        const formFields = {}
                        const name = mapjson[formPropertyApp.propertyFormationVM.editComponentData.property]
                        if (name) {
                            formFields[name] = {
                                value: formPropertyApp.propertyFormationVM.codeValue,
                            }
                            this.projectCommonFormRef.addSelAutoQueryForm.store.updateFormInputData(this.projectCommonFormRef.addSelAutoQueryForm.uid,formFields)
                        }
                        projectCommonApp.formSelectValueModalRef.viewModel.visible = true;
                        projectCommonApp.formAddKeyValueCodeExpressionModalRef.viewModel.visible = false;
                    }}></AddCodeExpression>
            </React.Fragment>
        )
    }
}